<?php

/**
 * 商品管理
 * Created by PhpStorm.
 * User: qinzhi
 * Date: 2017/06/30
 * Time: 12:01
 */
class Service_Goods
{

    const CART_COOKIE_PREFIX = '_ct';

    /**
     * 获取商品分类列表
     */
    public static function getCategoriesGoodsList(){
        $key = "goods_categories_goods_list";
        $categories = FCache::get($key);
        if(empty($categories)){
            $categoryTable = new FTable('goods_category','','xhs_slave');
            $categories = $categoryTable->where(array('status'=>1))->order('paixu desc')->select();
            foreach ($categories as &$category){
                $goodsTable = new FTable('goods','','xhs_slave');
                $dataList = $goodsTable->fields('auto_id,title,img1,img2,img3,purchase_price,price_old,price_new,freight,cs_num,paynum,is_banner,
                                        goodsection,num,brand,specification,brand,place_of_production,quality_guarantee_period,component,
                                        characteristic,is_soldout,is_purchasing')
                    ->where(array('status'=>1,'goodsection'=>$category['id']))->order('paixu desc,auto_id desc')->select();
                foreach ($dataList as $key=>$data){
                    $productTable = new FTable('product','','xhs_slave');
                    $products = $productTable->where(array("gid"=>$data['auto_id'],'pstatus'=>1))->select();
                    $dataList[$key]['pid'] = $products[0]['pid'];
                    $dataList[$key]['productList'] = $products;
                }
                $category['goods_list'] = $dataList;
            }
            FCache::set($key,$categories,300);
        }
        return $categories;
    }

    /**
     * 清除商品分类列表
     */
    public static function clearCategoriesGoodsListCache(){
        $key = "goods_categories_goods_list";
        FCache::delete($key);
    }

    /**
     * 获取推荐商品列表
     * @param int $limit
     * @return array|mixed
     */
    public static function getRecommendGoodsList($limit = 4){
        $goodsTable = new FTable('goods','','xhs_slave');
        $dataList = $goodsTable->fields('auto_id,title,img1,img2,img3,purchase_price,price_old,price_new,freight,cs_num,paynum,is_banner,
                                        goodsection,num,brand,specification,brand,place_of_production,quality_guarantee_period,component,
                                        characteristic,is_soldout,is_purchasing')
                                ->where(array('status'=>1,'goodsection'=>1))->order('paixu desc,auto_id desc')->limit($limit)->select();
        foreach ($dataList as $key=>$data){
            $productTable = new FTable('product','','xhs_slave');
            $products = $productTable->where(array("gid"=>$data['auto_id'],'pstatus'=>1))->select();
            $dataList[$key]['pid'] = $products[0]['pid'];
            $dataList[$key]['productList'] = $products;
        }
        return $dataList;
    }

    /**
     * 获取广告列表
     */
    public static function getBannerList(){
        $adTable = new FTable('ad','','xhs_slave');
        $bannerList = $adTable->where(array('status'=>1))->order('paixu desc')->select();
        return $bannerList;
    }

    /**
     * 获取商品列表页
     * @param $banner 1.广告推荐列表 2.不推荐列表
     * @param $page
     * @param int $limit
     * @return array|bool|mixed|null|string
     */
    public static function getGoodsList($banner,$page,$limit = 10){
        $page = $page < 0 ? 1 : $page;
        $key = "goods_list_{$page}_{$banner}";
        //$dataList = FCache::get($key);
        if (empty($dataList)) {
            $goodsTable = new FTable('goods','','xhs_slave');
            $dataList = $goodsTable->fields('auto_id,title,img1,img2,img3,purchase_price,price_old,price_new,freight,cs_num,paynum,is_banner,
                                        goodsection,num,brand,specification,brand,place_of_production,quality_guarantee_period,component,
                                        characteristic,is_soldout,is_purchasing')
                                    ->page($page)->limit($limit)->where(array('status'=>1,'is_banner'=>$banner))->order('paixu,auto_id desc')->select();
            foreach ($dataList as $key=>$data){
                $productTable = new FTable('product','','xhs_slave');
                $products = $productTable->where(array("gid"=>$data['auto_id'],'pstatus'=>1))->select();
                $dataList[$key]['pid'] = $products[0]['pid'];
                $dataList[$key]['productList'] = $products;
            }
            if(!empty($dataList))
                FCache::set($key,$dataList,300);
        }
        return $dataList;
    }

    /**
     * 清空列表页缓存
     * @param $banner
     */
    public static function clearGoodsListCache($banner = 2)
    {
        $key = "goods_list_";
        $page = 1;
        while (true) {
            $tk = $key . $page . $banner;
            $page = $page + 1;
            if (FCache::get($tk)){
                FCache::delete($tk);
            }else
                break;
        }
    }

    /**
     * 获取商品详情
     * @param $id
     * @return array|bool|mixed|null|string
     */
    public static function getGoods($id)
    {
        if ($id > 0) {
            $key = "goods_detail_{$id}";
            $data = FCache::get($key);
            if (empty($data)) {
                $goodsTable = new FTable('goods','','xhs_slave');
                $data = $goodsTable->where(array('auto_id' => $id))->find();
                $productTable = new FTable('product','','xhs_slave');
                $products = $productTable->where(array("gid"=>$data['auto_id'],'pstatus'=>1))->select();
                $data['pid'] = $products[0]['pid'];
                $data['productList'] = $products;
                if (!empty($data))
                    FCache::set($key, $data, 1800);
            }
            return $data;
        }
        return false;
    }

    /**
     * 清空商品缓存
     * @param $id
     */
    public static function clearGoodsCache($id)
    {
        if ($id > 0) {
            $key = "goods_detail_{$id}";
            FCache::delete($key);
        }
    }

    /**
     * 获取购物车列表
     * @return bool|array|null
     */
    public static function getCartGoods()
    {
        global $_F;
        $cartList = FCookie::get(self::CART_COOKIE_PREFIX);
        if (!empty($cartList)) {
            $cartList = json_decode($cartList, true);
            if ($cartList) {
                $pidList = array();
                foreach ($cartList as $cart) {
                    if (isset($pidList[$cart['id']])) {
                        $pidList[$cart['id']] += $cart['n'];
                    } else {
                        $pidList[$cart['id']] = $cart['n'];
                    }
                }
                $productT = new FTable('product','t1','xhs_slave');
                $dataList = $productT->fields('t1.*,t2.title,t2.unit,t2.img2,t2.img3')
                                    ->leftJoin('goods','t2','t1.gid=t2.auto_id')
                                        ->where(array('pid'=>array('in'=>array_keys($pidList)),'t2.status'=>1))->select();

                $cartList = array();
                foreach ($dataList as $key => $data) {
                    if ($pidList[$data['pid']] > 0) {
                        $cartList[] = array(
                            'id' => $data['pid'],
                            'n' => $pidList[$data['pid']],
                        );
                        $dataList[$key]['cart_num'] = $pidList[$data['pid']];
                        $spec_list = $data['spec_list'];
                        $spec_str = '';
                        if($spec_list){
                            $spec_list = json_decode($spec_list,true);
                            foreach ($spec_list as $spec){
                                $spec = json_decode($spec,true);
                                $spec_str .= ',' . $spec['value'];
                            }
                            $spec_str = substr($spec_str,1);
                        }
                        $dataList[$key]['spec_str'] = $spec_str;
                    } else
                        unset($dataList[$key]);
                }
                FCookie::set(self::CART_COOKIE_PREFIX, json_encode($cartList), 86400 * 30);
                return $dataList;
            }
        }
        FCookie::remove(self::CART_COOKIE_PREFIX);
        return null;
    }

    /**
     * 更新购物车
     * @param int $id
     * @param $num $id
     * @return bool|array
     */
    public static function updateCart($id, $num = 1)
    {

        if ($id) {
            $goods = self::getGoods($id);
            if ($goods) {
                $cartList = FCookie::get(self::CART_COOKIE_PREFIX);
                $exist = false;
                if (!empty($cartList)) {
                    $cartList = json_decode($cartList, true);
                    foreach ($cartList as $key=>&$cart) {
                        if ($cart['id'] == $id) {
                            $cart['n'] += $num;
                            if($cart['n']<=0||$num==0){  //数量小于0,直接删除
                                unset($cartList[$key]);
                            }
                            $exist = true;
                            break;
                        }
                    }
                }
                if (!$exist) {
                    $cartList[] = array('id' => $id, 'n' => $num);
                }
                FCookie::set(self::CART_COOKIE_PREFIX, json_encode($cartList), 86400 * 30);
                return true;
            }
        }
        return false;
    }

    // 末尾金额去零 如果带小数点 就去小数点
    public static function moneyReZero($money){
        $money = rtrim($money,'0');
        $money = rtrim($money,'.');
        return $money;
    }

    /**
     * 清空购物车
     */
    public static function clearCart(){
        FCookie::remove(self::CART_COOKIE_PREFIX);
    }
}